package com.google.code.sfa.parse;

import org.biojava.bio.*;
import org.biojava.bio.seq.*;
import org.biojava.bio.seq.db.*;
import org.biojava.bio.seq.io.*;
import org.biojava.bio.symbol.*;
import java.util.Map;
import java.util.HashMap;

public class Trace implements Comparable<Trace> {

    private SymbolList _seq;
    private SymbolList _seqReverseComplement;
    private String _id;
    private String _cloneId;
    private boolean _forward;
    private Trace _mate;
    private Map<Trace,Integer> _matches;
    private boolean _repeat;
    private boolean _reversed;

    public Trace( String id, String cloneId, SymbolList sequence, boolean forward) {
	_id = id;
	_cloneId = cloneId;
	_seq = sequence;
	_forward = forward;
	_repeat = false;
	_reversed = false;
	_seqReverseComplement = null;
    }

    public void setMate( Trace mate) {
	_mate = mate;
    }

    public void setMatches( Map<Trace,Integer> matches) {
	_matches = matches;
    }
    
    public int getMatchesSize() {
	return _matches.size();
    }

    public Map<Trace,Integer> getMatches() {
	return _matches;
    }

    public void setRepeat() {
	_repeat = true;
    }
    public boolean isRepeat() {
	return _repeat;
    }

    public String getId() {
	return _id + ((_reversed)?"'":"");
    }

    public String getCloneId() {
	return _cloneId;
    }

    public boolean getForward() {
	return _forward;
    }

    public SymbolList getSequence() {
	if( _reversed ) {
	    return _seqReverseComplement;
	} else {
	    return _seq;
	}
    }

    public void reverse() {
	_reversed = !_reversed;
	if( _reversed && _seqReverseComplement == null) {
	    try {
		_seqReverseComplement = DNATools.reverseComplement( _seq);
	    } catch( IllegalAlphabetException e) {
		e.printStackTrace();
	    }
	}
    }

    public void insertGap(int pos) {
	SimpleGappedSymbolList g;
	if( _reversed) {
	    if( ! (_seqReverseComplement instanceof SimpleGappedSymbolList)) {
		g = new SimpleGappedSymbolList( _seqReverseComplement);
	    } else {
		g = (SimpleGappedSymbolList) _seqReverseComplement;
	    }
	    g.addGapInView( pos);
	    _seqReverseComplement = g;
	} else {
	    if( ! (_seq instanceof SimpleGappedSymbolList)) {
		g = new SimpleGappedSymbolList( _seq);
	    } else {
		g = (SimpleGappedSymbolList) _seq;
	    }
	    g.addGapInView( pos);
	    _seq = g;
	}
    }
	

    public String toString() {
	return getId() + ((_forward)?" -> ":" <- ") + ((_mate != null)?_mate.getId():"") + "\n" + 
	    _seq.seqString() + "\n";
    } 

    public int compareTo( Trace other) {
	return _matches.size() - other._matches.size();
    }

}

